package com.vhr.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vhr.VO.LeaveVO;
import com.vhr.entities.*;
import com.vhr.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(value = "LeaveController", description = "请假模块")
@Controller
@CrossOrigin(allowCredentials="true",allowedHeaders="*")
@Transactional
public class LeaveController {
    @Autowired
    public ILeaveService iLeaveService;
    @Autowired
    public AccountService accountService;
    @Autowired
    private IEmployeeService iEmployeeService;
    @Autowired
    private ICheckService iCheckService;
    @Autowired
    private IDepartmentService iDepartmentService;

    List<LeaveVO> leaveVOList = null;

    public List<LeaveVO> dateForm(List<Leave> leaveList ){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<LeaveVO> leaveVOList1 = new ArrayList<>();
        for(Leave list : leaveList){
            LeaveVO leaveVO = new LeaveVO();
            leaveVO.setLeaveId(list.getLeaveId());
            leaveVO.setLeaveReason(list.getLeaveReason());
            leaveVO.setLeaveStart(sdf.format(list.getLeaveStart()));
            leaveVO.setLeaveEnd(sdf.format(list.getLeaveEnd()));
            leaveVO.setLeaveStatus(list.getLeaveStatus());
            leaveVO.setEmpId(list.getEmpId());
            Employee employee = new Employee();
            employee.setEmpId(list.getEmpId());
            leaveVO.setEmpNum(accountService.selectEmployeeByEmpId(list.getEmpId()).getEmpNum());
            leaveVO.setEmpName(iEmployeeService.selectEmployeeByPrimaryKey(employee).getEmpName());
            leaveVO.setJudgeId(list.getJudgeId());
//            System.err.println("JudegeId = " + list.getJudgeId());
            employee = new Employee();;

            if(list.getJudgeId() != null){
                employee.setEmpId(list.getJudgeId());
//                System.out.println("employee: " + employee.toString());
                leaveVO.setJudgeName(iEmployeeService.selectEmployeeByPrimaryKey(employee).getEmpName());
            }
            else{
                leaveVO.setJudgeName(null);
            }

            leaveVO.setLeaveDuration(list.getLeaveDuration());
            leaveVO.setSubmitTime(sdf.format(list.getSubmitTime()));
            employee = new Employee();;
            employee.setEmpId(list.getEmpId());
            Employee emp = iEmployeeService.selectEmployeeByPrimaryKey(employee);
            leaveVO.setDeptId(iDepartmentService.selectDepartmentByDeptId(emp.getDeptId()).getDeptId());
            leaveVO.setDeptName(iDepartmentService.selectDepartmentByDeptId(emp.getDeptId()).getDeptName());
//            System.err.println("department: " + iDepartmentService.selectDepartmentByDeptId(emp.getDeptId()).getDeptName());
            leaveVOList1.add(leaveVO);
        }
        return leaveVOList1;
    }

    public <T> MyPageInfo myPageInfo(PageInfo pageInfo, List<LeaveVO> leaveVOList){
        MyPageInfo<LeaveVO> myPageInfo = new MyPageInfo<>();
        myPageInfo.setList(leaveVOList);
        myPageInfo.setPageNum(pageInfo.getPageNum());
        myPageInfo.setPageSize(pageInfo.getPageSize());
        myPageInfo.setRecordCount((int)pageInfo.getTotal());
        myPageInfo.setTotalPage(pageInfo.getPages());
        return myPageInfo;
    }



    //    管理员查询所有请假申请记录
    @GetMapping("/api/leave/listAllLeave")
    @ResponseBody
    @ApiOperation("管理员查询所有请假申请记录")
    @ApiImplicitParam(name = "pn", required = false, paramType = "query", value = "页码", dataType = "Integer", defaultValue = "1")
    public Result listAllLeave(@RequestParam(value = "pn", defaultValue = "1") Integer pn){
        PageHelper.startPage(pn, 8);
        List<Leave> leaveList = iLeaveService.selectAll();
        if(leaveList.size() == 0)
            return Result.fail();
        PageInfo pageInfo = new PageInfo(leaveList, 3);
        leaveVOList = dateForm(leaveList);
        MyPageInfo<LeaveVO> myPageInfo = myPageInfo(pageInfo, leaveVOList);
        return Result.success().add("myPageInfo", myPageInfo);
    }

    //管理员按日期段查看请假记录


    //    管理员条件模糊搜索查询请假申请记录
    @GetMapping("/api/leave/listLeaveByCondition")
    @ResponseBody
    @ApiOperation("管理员条件模糊搜索查询请假申请记录")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "deptId", paramType = "query", value = "部门id", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "empName", paramType = "query", value = "员工姓名", required = false, dataType = "String"),
        @ApiImplicitParam(name = "status", paramType = "query", value = "审批状态", required = false, dataType = "Integer"),
         @ApiImplicitParam(name = "pn", required = false, paramType = "query", value = "页码", dataType = "Integer")
    })
    public Result listLeaveByCondition(@RequestParam(value = "deptId", required = false)Integer deptId, @RequestParam(value = "empName", required = false)String empName, @RequestParam(value = "status", defaultValue = "-1")Integer status, @RequestParam(value = "pn", defaultValue = "1", required = false)Integer pn){
//        System.err.println(deptId);
//        System.err.println(empName);
//        PageHelper.startPage(pn, 6);
//        List<Leave> leaveList = iLeaveService.selectCheckByCondition(deptId, empName);
//        if(leaveList.size() == 0)
//            return Result.fail();
        PageInfo pageInfo = iLeaveService.selectCheckByCondition(pn, deptId, empName, status);
        if(pageInfo == null)
            return Result.fail();
        List<Leave> leaveList = new ArrayList<>();
        List<Leave> list = pageInfo.getList();

        for(Leave leave : list){
            leaveList.add(leave);
        }
        leaveVOList = dateForm(leaveList);
        MyPageInfo<LeaveVO> myPageInfo = myPageInfo(pageInfo, leaveVOList);
        return Result.success().add("myPageInfo", myPageInfo);
//        return Result.success().add("pageInfo", pageInfo);
    }


    //管理员查看未审批消息
    @GetMapping("/api/leave/listLeaveApprovalMessage")
    @ResponseBody
    @ApiOperation("管理员查看未审批消息")
//    @ApiImplicitParams(value = {
//            @ApiImplicitParam(name = "empNum", value = "员工编号", dataType = "int"),
    @ApiImplicitParam(name = "pn", required = false, paramType = "query", value = "页码", dataType = "Integer")
//    })
    public Result listLeaveApprovalMessage(@RequestParam(value = "pn", defaultValue = "1", required = false) Integer pn){
        PageHelper.startPage(pn, 8);
        List<Leave> leaveList = iLeaveService.selectWithoutJudge();
        if(leaveList.size() == 0)
            return Result.fail();
        PageInfo pageInfo = new PageInfo(leaveList, 6);
        leaveVOList = dateForm(leaveList);
        MyPageInfo<LeaveVO> myPageInfo = myPageInfo(pageInfo, leaveVOList);
        return Result.success().add("myPageInfo", myPageInfo);

    }

    //管理员批改申请
    @PutMapping("/api/leave/updateLeaveStatus")
    @ResponseBody
    @ApiOperation("管理员批改申请")
    @ApiImplicitParams(value={
            @ApiImplicitParam(name = "leaveId", paramType = "query", required = true, value = "请假记录id", dataType = "Integer"),
            @ApiImplicitParam(name = "judgeId", paramType = "query", required = true, value = "审批者id", dataType = "Integer"),
            @ApiImplicitParam(name = "status", paramType = "query", required = true, value = "审批状态码", dataType = "Integer")
    })
    public Result updateLeaveStatus(@RequestParam(value = "leaveId", required = true) Integer leaveId, @RequestParam(value = "judgeId", required = true) Integer judgeId, @RequestParam("status") Integer status) throws Exception{
        Leave leave = iLeaveService.selectByPrimary(leaveId);
        leave.setJudgeId(judgeId);
        leave.setLeaveStatus(status);
        int i = iLeaveService.updateByPrimary(leave);
        if(i == 0)
            return Result.fail();
        Leave leave1 = leave;
        if(status == 1){
            Check check = new Check();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            LocalDate localDate1 = leave.getLeaveStart().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDate localDate2 = leave.getLeaveEnd().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            int days = (int) localDate1.until(localDate2, ChronoUnit.DAYS);
            System.out.println("days:" + days);
            for(int l = 0; l <= days; l++){
                Date date = Date.from((localDate1.plus(l, ChronoUnit.DAYS)).atStartOfDay(ZoneId.systemDefault()).toInstant());
                System.err.println("date: " + date);
//                leave.getLeaveStart().setMonth(date.getMonth());
//              leave.getLeaveStart().setDate(date.getDate());
                String dateForm = sdf.format(date);
                check.setCurrentDate(sdf.parse(dateForm));
                check.setSgininTime(leave.getLeaveStart());
                check.setSignbackTime(leave.getLeaveEnd());
                check.setEmpId(leave.getEmpId());
                check.setCheckStatus(2);
                System.out.println("leaveStart = " + leave.getLeaveStart());
                int j = iCheckService.insertCheck(check);
                if(j == 0)
                    return Result.fail();
            }
        }

        return Result.success();
    }

    //管理员删除审批记录
    @PutMapping("/api/leave/deleteLeave")
    @ResponseBody
    @ApiOperation("管理员删除审批记录")
    @ApiImplicitParams(value={
            @ApiImplicitParam(name = "leaveId", paramType = "query", required = true, value = "请假记录id", dataType = "Integer"),
    })
    public Result deleteLeave(@RequestParam(value = "leaveId", required = true) Integer leaveId) throws Exception{
        Leave leave = new Leave();
        leave.setLeaveId(leaveId);
        int i = iLeaveService.deleteByPrimary(leave);
        if(i == 0)
            return Result.fail();
        return Result.success();
    }



    //员工查看自己所有请假申请记录
    @GetMapping("/leave/listLeaveByEmpId")
    @ResponseBody
    @ApiOperation("员工查看自己所有请假申请记录")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "empId", required = true, paramType = "query", value = "员工id", dataType = "Integer"),
            @ApiImplicitParam(name = "pn", paramType = "query", value = "页码", dataType = "Integer"),
    })
    public Result listLeaveByEmpId(@RequestParam(value = "empId", required = true) Integer empId, @RequestParam(value = "pn", defaultValue = "1") Integer pn){
//        int empId = accountService.selectEmployeeByEmpNum(empNum).getEmpId();
        Employee employee = new Employee();
        employee.setEmpId(empId);
        PageHelper.startPage(pn, 6);
        List<Leave> leaveList = iLeaveService.selectByEmployee(employee);
        if(leaveList.size() == 0)
            return Result.fail();

        PageInfo pageInfo = new PageInfo(leaveList, 6);
        leaveVOList = dateForm(leaveList);
        MyPageInfo<LeaveVO> myPageInfo = myPageInfo(pageInfo, leaveVOList);
        return Result.success().add("myPageInfo", myPageInfo);
    }

    //员工条件查看自己请假是否审批通过记录
    @GetMapping("/leave/listLeaveAllowNot")
    @ResponseBody
    @ApiOperation("员工条件查看自己请假是否审批通过记录")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "empId", required = true, paramType = "query", value = "员工id", dataType = "Integer"),
            @ApiImplicitParam(name = "status", paramType = "query", value = "申请状态", dataType = "Integer"),
            @ApiImplicitParam(name = "pn", paramType = "query", value = "页码", dataType = "Integer"),
    })
    public Result listLeaveAllowNot(@RequestParam(value = "empId", required = true) Integer empId, @RequestParam(value = "status", defaultValue = "-1") Integer status,  @RequestParam(value = "pn", defaultValue = "1") Integer pn){
//        int empId = accountService.selectEmployeeByEmpNum(empNum).getEmpId();
        PageHelper.startPage(pn, 6);
        List<Leave> leaveList = iLeaveService.selectLeaveAllowNot(empId, status);
        if(leaveList.size() == 0)
            return Result.fail();
        PageInfo pageInfo = new PageInfo(leaveList, 6);

        leaveVOList = dateForm(leaveList);
        MyPageInfo<LeaveVO> myPageInfo = myPageInfo(pageInfo, leaveVOList);
        return Result.success().add("myPageInfo", myPageInfo);
    }

    //    员工提交请假申请
    @PostMapping("/leave/insertLeave")
    @ResponseBody
    @ApiOperation("员工提交请假申请")
//    @ApiImplicitParams(value = {
//            @ApiImplicitParam(name = "reason", paramType = "query", required = true, value = "请假原因", dataType = "java.lang.String"),
//            @ApiImplicitParam(name = "start_date", paramType = "query", required = true, value = "起始日期", dataType = "Date"),
//            @ApiImplicitParam(name = "end_date",  paramType = "query", required = true, value = "结束日期", dataType = "Date"),
//            @ApiImplicitParam(name = "empId", required = true, paramType = "query", value = "员工编号", dataType = "int")
            @ApiImplicitParam(name = "leave", required = true, paramType = "body", value = "请假对象", dataType = "com.vhr.entities.Leave")
//    })
//    public Result insertLeave(@RequestParam(value = "reason", required = true) String reason, @RequestParam(value = "start_date", required = true) Date start_date, @RequestParam(value = "end_date", required = true) Date end_date, @RequestParam(value = "empId", required = true) int empId) throws Exception{
    public Result insertLeave(@RequestBody Leave leave) throws Exception{
//        int empId = accountService.selectEmployeeByEmpNum(empNum).getEmpId();

        if(leave.getLeaveStart().getHours() < 8 || leave.getLeaveStart().getHours() > 18 || leave.getLeaveEnd().getHours() < 8 || leave.getLeaveEnd().getHours() > 18 || leave.getLeaveStart().compareTo(leave.getLeaveEnd()) > 0){
            return Result.fail().add("Msg", "请传入正确的时间(8-18点)");
        }
        //Leave leave = new Leave();
        //leave.setLeaveReason(leaveReason);
        //leave.setLeaveStart(leaveStart);
        //leave.setLeaveEnd(leaveEnd);
//        System.err.println(leave);
        leave.setLeaveStatus(0);
//        leave.setEmpId(empId);
        leave.setJudgeId(null);
        //判断请假多少个小时
        SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");
        //Date startTime = sdfTime.parse("12:00:00");
        //Date endTime = sdfTime.parse("14:00:00");
        Date start_date = leave.getLeaveStart();
        Date end_date = leave.getLeaveEnd();
        //startTime.setDate(start_date.getDate());
        //startTime.setMonth(start_date.getMonth());
        //startTime.setYear(start_date.getYear());
        //endTime.setDate(end_date.getDate());
        //endTime.setMonth(end_date.getMonth());
        //endTime.setYear(end_date.getYear());
        int dateHours = (int)(end_date.getTime() - start_date.getTime()) / 1000 / 3600;
        System.out.println("dateHours:" + dateHours);
        int dates = dateHours / 12;
        System.out.println("dates = " + dates);
        int hours = dates * 8;
        /*if(end_date.getHours() <= 18 && start_date.getHours() >= 8){
            System.out.println("1=" + Math.round( (double)(startTime.getTime() - start_date.getTime()) / 1000 / 3600) + Math.round((double)(end_date.getTime() - endTime.getTime())/ 1000 / 3600));
            hours += Math.round( (double)(startTime.getTime() - start_date.getTime()) / 1000 / 3600) + Math.round((double)(end_date.getTime() - endTime.getTime())/ 1000 / 3600);
        }
        else if( (start_date.getHours() >= 8 && end_date.getHours() <= 12) || (start_date.getHours() >= 14 && end_date.getHours() <= 18) ) {
            System.out.println("2="+Math.round((double)(end_date.getTime() - start_date.getTime()) / 1000 / 3600));
            hours += Math.round((double)(end_date.getTime() - start_date.getTime()) / 1000 / 3600);
        }*/
        //if(hours > 0){
            if(end_date.getHours() <= 12){
                //早上
                Date startTime = sdfTime.parse("8:00:00");
                startTime.setDate(end_date.getDate());
                startTime.setMonth(end_date.getMonth());
                startTime.setYear(end_date.getYear());
                System.out.println("startTime = " + startTime);
                System.out.println("end_date = " + end_date);
                System.out.println("1 = " + Math.round((long)(end_date.getTime() - startTime.getTime()) / 1000 / 3600));
                Double d;
                hours += Math.round((end_date.getTime() - startTime.getTime()) / 1000 / 3600);
            }
            else if(start_date.getHours() >= 14 && end_date.getHours() <= 18){
                //下午
                Date endTime = sdfTime.parse("14:00:00");
                endTime.setDate(end_date.getDate());
                endTime.setMonth(end_date.getMonth());
                endTime.setYear(end_date.getYear());
                System.out.println("endTime = " + endTime);
                System.out.println("end_date = " + end_date);
                System.out.println("2 = " + Math.round((long)(end_date.getTime() - endTime.getTime()) / 1000 / 3600));
                hours += Math.round((end_date.getTime() - endTime.getTime()) / 1000 / 3600);
            }
            else{
                //全天
                Date startTime = sdfTime.parse("12:00:00");
                /*startTime.setDate(end_date.getDate());
                startTime.setMonth(end_date.getMonth());
                startTime.setYear(end_date.getYear());*/
                Date endTime = sdfTime.parse("14:00:00");
                endTime.setDate(end_date.getDate());
                endTime.setMonth(end_date.getMonth());
                endTime.setYear(end_date.getYear());
                //System.out.println("startTime = " + startTime + "  ---endTime = " + endTime);
                System.out.println("start_date = " + start_date + "  ---end_date = " + end_date);
                System.out.println("3 = " + Math.round((long)(end_date.getTime() - endTime.getTime())/ 1000 / 3600));
                hours +=  Math.round((end_date.getTime() - endTime.getTime())/ 1000 / 3600);
                hours += 4;
            }
        //}
        /*else{
            *//*System.out.println("4 = " + Math.round((double)(end_date.getTime() - start_date.getTime()) / 1000 / 3600));
            hours += Math.round((double)(end_date.getTime() - start_date.getTime()) / 1000 / 3600);*//*
            if(end_date.getHours() <= 12){
                //早上
                Date startTime = sdfTime.parse("8:00:00");
                startTime.setDate(end_date.getDate());
                startTime.setMonth(end_date.getMonth());
                startTime.setYear(end_date.getYear());
                System.out.println("startTime = " + startTime);
                System.out.println("end_date = " + end_date);
                System.out.println("1 = " + Math.round((long)(end_date.getTime() - startTime.getTime()) / 1000 / 3600));
                hours += Math.round((long)(end_date.getTime() - startTime.getTime()) / 1000 / 3600);
            }
            else if(start_date.getHours() >= 14 && end_date.getHours() <= 18){
                //下午
                Date endTime = sdfTime.parse("14:00:00");
                endTime.setDate(end_date.getDate());
                endTime.setMonth(end_date.getMonth());
                endTime.setYear(end_date.getYear());
                System.out.println("endTime = " + endTime);
                System.out.println("end_date = " + end_date);
                System.out.println("2 = " + Math.round((long)(end_date.getTime() - endTime.getTime()) / 1000 / 3600));
                hours += Math.round((long)(end_date.getTime() - endTime.getTime()) / 1000 / 3600);
            }
            else{
                //全天
                Date startTime = sdfTime.parse("12:00:00");
                *//*startTime.setDate(end_date.getDate());
                startTime.setMonth(end_date.getMonth());
                startTime.setYear(end_date.getYear());*//*
                Date endTime = sdfTime.parse("14:00:00");
                endTime.setDate(end_date.getDate());
                endTime.setMonth(end_date.getMonth());
                endTime.setYear(end_date.getYear());
                //System.out.println("startTime = " + startTime + "  ---endTime = " + endTime);
                System.out.println("start_date = " + start_date + "  ---end_date = " + end_date);
                System.out.println("3 = " + Math.round((long)(end_date.getTime() - endTime.getTime())/ 1000 / 3600));
                hours +=  Math.round((long)(end_date.getTime() - endTime.getTime())/ 1000 / 3600);
                hours += 4;
            }
        }*/
        System.err.println("hours: " + hours);
        leave.setLeaveDuration(hours);
        leave.setSubmitTime(new Date());

        int i = iLeaveService.addLeave(leave);
        if(i == 0)
            return Result.fail();
        return Result.success();
    }

}
